<template>
    <view class="container">
        <!-- 页面标题 -->
        <view class="page-title">新增员工信息</view>
        
        <!-- 表单容器 -->
        <view class="form-container">
            <!-- 姓名字段 -->
            <view class="form-item">
                <view class="form-label">姓名</view>
                <view class="form-input-wrapper">
                    <input type="text" class="form-input" v-model="employee.name" placeholder="请输入姓名" @blur="generateLoginName" />
                </view>
            </view>
            
            <!-- 性别字段 -->
            <view class="form-item">
                <view class="form-label">性别</view>
                <view class="form-radio-group">
                    <radio-group v-model="employee.gender">
                        <label class="form-radio-item" v-for="(item, index) in genders" :key="index">
                            <radio :value="item.value" />
                            <view class="radio-text">{{ item.label }}</view>
                        </label>
                    </radio-group>
                </view>
            </view>
            
            <!-- 手机号字段 -->
            <view class="form-item">
                <view class="form-label">手机号</view>
                <view class="form-input-wrapper">
                    <input type="tel" class="form-input" v-model="employee.phone" placeholder="请输入手机号" @blur="generateLoginName" />
                </view>
            </view>
            
            <!-- 登录名字段 -->
            <view class="form-item">
                <view class="form-label">登录名</view>
                <view class="form-input-wrapper">
                    <input type="text" class="form-input" v-model="employee.loginName" placeholder="系统自动生成" disabled :placeholder-style="employee.loginName ? 'color:#999' : 'color:#ccc'" />
                </view>
                <view class="auto-gen-tip" v-if="employee.loginName">系统自动生成：姓名全拼+手机号后四位</view>
            </view>
            
            <!-- 密码字段 -->
            <view class="form-item">
                <view class="form-label">初始化密码：yc123456</view>
                          </view>
            
            <!-- 身份证号字段 -->
            <view class="form-item">
                <view class="form-label">身份证号</view>
                <view class="form-input-wrapper">
                    <input type="idcard" class="form-input" v-model="employee.idCard" placeholder="请输入身份证号" />
                </view>
            </view>
            
            <!-- 出生日期字段 -->
            <view class="form-item">
                <view class="form-label">出生日期</view>
                <view class="form-input-wrapper">
                    <picker mode="date" :value="employee.birthday" start="1900-01-01" end="2025-12-31" @change="onBirthdayChange">
                        <view class="picker">
                            {{ employee.birthday || '请选择出生日期' }}
                        </view>
                    </picker>
                </view>
            </view>
            
            <!-- 本人相片上传 -->
            <view class="form-item">
                <view class="form-label">本人相片上传</view>
                <view class="form-upload-wrapper">
                    <view class="upload-item" v-if="personalPhoto">
                        <image :src="personalPhoto[0]" mode="aspectFill" class="upload-preview"></image>
                        <view class="upload-delete" @click="removePersonalPhoto">×</view>
                    </view>
                    <view class="upload-btn" @click="chooseImage('personalPhoto')" v-if="!personalPhoto">
                        <view class="upload-icon">+</view>
                        <view class="upload-text">上传本人相片</view>
                    </view>
                    <view class="upload-tip">请上传个人免冠照片</view>
                </view>
            </view>
            
            <!-- 入职时间 -->
            <view class="form-item">
                <view class="form-label">入职时间</view>
                <view class="form-input-wrapper">
                    <picker mode="date" :value="employee.hireDate" start="2000-01-01" end="2025-12-31" @change="onHireDateChange">
                        <view class="picker">
                            {{ employee.hireDate || '请选择入职时间' }}
                        </view>
                    </picker>
                </view>
            </view>
            
            <!-- 合同有效期 -->
            <view class="form-item">
                <view class="form-label">合同有效期</view>
                <view class="form-input-wrapper">
                    <picker mode="date" :value="employee.contractStartDate" start="2000-01-01" end="2025-12-31" @change="onContractStartDateChange">
                        <view class="picker">
                            {{ employee.contractStartDate || '请选择合同开始日期' }}
                        </view>
                    </picker>
                    <view class="date-separator">-</view>
                    <picker mode="date" :value="employee.contractEndDate" start="2000-01-01" end="2030-12-31" @change="onContractEndDateChange">
                        <view class="picker">
                            {{ employee.contractEndDate || '请选择合同结束日期' }}
                        </view>
                    </picker>
                </view>
            </view>
            
            <!-- 身份证上传 -->
            <view class="form-item">
                <view class="form-label">身份证上传</view>
                <view class="form-upload-wrapper">
                    <view class="upload-item" v-for="(item, index) in idCardImages" :key="index">
                        <image :src="item" mode="aspectFill" class="upload-preview"></image>
                        <view class="upload-delete" @click="removeImage('idCardImages', index)">×</view>
                    </view>
                    <view class="upload-btn" @click="chooseImage('idCardImages')" v-if="idCardImages.length < 2">
                        <view class="upload-icon">+</view>
                        <view class="upload-text">上传身份证</view>
                    </view>
                    <view class="upload-tip">请上传正反面照片（最多2张）</view>
                </view>
            </view>
            
            <!-- 劳动合同上传 -->
            <view class="form-item">
                <view class="form-label">劳动合同文件上传</view>
                <view class="form-upload-wrapper">
                    <view class="upload-file-item" v-if="contractFile.name">
                        <text class="file-name">{{ contractFile.name }}</text>
                        <text class="file-size">{{ contractFile.size }}</text>
                        <text class="file-delete" @click="removeFile">×</text>
                    </view>
                    <view class="upload-btn" @click="chooseFile" v-if="!contractFile.name">
                        <view class="upload-icon">+</view>
                        <view class="upload-text">上传劳动合同</view>
                    </view>
                    <view class="upload-tip">支持 PDF、Word 格式文件</view>
                </view>
            </view>
        </view>
        
        <!-- 提交按钮 -->
        <view class="submit-btn" @click="submitForm">提交</view>
    </view>
</template>

<script>
	import { pinyin } from 'pinyin-pro'
	const uniIdCo=uniCloud.importObject('uni-id-co')
export default {
    data() {
        return {
            employee: {
                name: '',
                gender: 'male',
                phone: '',      // 新增：手机号
                loginName: '',  // 新增：登录名
                password: '',   // 新增：密码
                idCard: '',
                birthday: '',
                hireDate: '',
                contractStartDate: '',
                contractEndDate: '',
            },
            genders: [
                { label: '男', value: 'male' },
                { label: '女', value: 'female' }
            ],
            personalPhoto: [],
            idCardImages: [],
            contractFile: []
        }
    },
    methods: {
        // 生成登录名（姓名全拼+手机号后四位）
        generateLoginName() {
            if (this.employee.name && this.employee.phone) {
                // 这里简化处理，实际项目中需要使用拼音转换库
                // 例如：pinyin-pro 或其他拼音转换工具
                const phoneLastFour = this.employee.phone.slice(-4);
                // 简单拼音转换模拟（实际项目需要替换为真实拼音转换）
                const pinyin = this.simplifiedPinyin(this.employee.name);
                this.employee.loginName = `${pinyin}${phoneLastFour}`;
            } else {
                this.employee.loginName = '';
            }
        },
        
        // 简化的拼音转换（仅作示例，实际项目需替换为真实拼音转换库）
        simplifiedPinyin(name) {
      
            const str=  pinyin(name, { toneType: 'none', type: 'string' });
             return str.replace(/\s/g, '')
           },
        
        // 选择出生日期
        onBirthdayChange(e) {
            this.employee.birthday = e.detail.value;
        },
 

        // 移除本人照片
        removePersonalPhoto() {
            this.personalPhoto = '';
        },
        
        // 选择入职时间
        onHireDateChange(e) {
            this.employee.hireDate = e.detail.value;
        },
        
        // 选择合同开始日期
        onContractStartDateChange(e) {
            this.employee.contractStartDate = e.detail.value;
            // 如果结束日期早于开始日期，重置结束日期
            if (this.employee.contractEndDate && this.employee.contractEndDate < this.employee.contractStartDate) {
                this.employee.contractEndDate = '';
            }
        },
        
        // 选择合同结束日期
        onContractEndDateChange(e) {
            this.employee.contractEndDate = e.detail.value;
        },
		async uploadFile(url,id,type){
	
			uni.uploadFile({
			  filePath:url,
			  cloudPath:`/${type}/${this.employee.loginName}-${id}`,
			    success: (res) => {
			    console.log(res);
				 
			    }
			});
		},
		
        
        // 选择图片
        chooseImage(type) {
            uni.chooseImage({
                count: type === 'idCardImages' ? 2 - this.idCardImages.length : 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: (res) => {
			         if (type === 'idCardImages') {
                        this.idCardImages = [...this.idCardImages, ...res.tempFilePaths];
    	
					}else{
						this.personalPhoto=[res.tempFilePaths[0]]
					}
                
				
				}	
            });
        },
        
        // 移除图片
        removeImage(type, index) {
            if (type === 'idCardImages') {
                this.idCardImages.splice(index, 1);
            }
        },
        
        // 选择文件
        chooseFile() {
			const _this=this			
			uni.chooseFile({
				success(res) {
				_this.contractFile=	res.tempFilePaths
				}
			})
           
        },
        
        // 移除文件
        removeFile() {
            this.contractFile = {};
        },
        
        // 格式化文件大小
        formatSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        },
        
        // 提交表单
     async   submitForm() {
		
		        // uni.showLoading({
		        //     title: '上传中...',
		        //     mask: true
		        // });
				const id=[]
	     for(let i=0;i<this.idCardImages.length-1;i++){
			 console.log("22",this.idCardImages[i]);
		     this.uploadFile(this.idCardImages[i],i,'idCardImages')
			 
		 }  
	
		 return
		 
		 
		 
		 
		 
		const res=	await uniIdCo.addUser({
				username:this.employee.loginName,
				password:"yc123456"
				
			})
			console.log("....reg",res);
			
            // 表单验证
            if (!this.employee.name) {
                uni.showToast({
                    title: '请输入姓名',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.phone) {
                uni.showToast({
                    title: '请输入手机号',
                    icon: 'none'
                });
                return;
            }
            
            // 手机号验证
            const phoneReg = /^1[3-9]\d{9}$/;
            if (!phoneReg.test(this.employee.phone)) {
                uni.showToast({
                    title: '手机号格式不正确',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.loginName) {
                uni.showToast({
                    title: '无法自动生成登录名，请检查姓名和手机号',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.password) {
                uni.showToast({
                    title: '请设置密码',
                    icon: 'none'
                });
                return;
            }
            
                
            if (!this.employee.idCard) {
                uni.showToast({
                    title: '请输入身份证号',
                    icon: 'none'
                });
                return;
            }
            
            // 身份证号简单验证
            const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if (!idCardReg.test(this.employee.idCard)) {
                uni.showToast({
                    title: '身份证号格式不正确',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.birthday) {
                uni.showToast({
                    title: '请选择出生日期',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.personalPhoto) {
                uni.showToast({
                    title: '请上传本人照片',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.hireDate) {
                uni.showToast({
                    title: '请选择入职时间',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.employee.contractStartDate || !this.employee.contractEndDate) {
                uni.showToast({
                    title: '请选择完整的合同有效期',
                    icon: 'none'
                });
                return;
            }
            
            // 验证合同日期逻辑
            if (this.employee.contractStartDate >= this.employee.contractEndDate) {
                uni.showToast({
                    title: '合同结束日期必须晚于开始日期',
                    icon: 'none'
                });
                return;
            }
            
            if (this.idCardImages.length === 0) {
                uni.showToast({
                    title: '请上传身份证照片',
                    icon: 'none'
                });
                return;
            }
            
            if (!this.contractFile.name) {
                uni.showToast({
                    title: '请上传劳动合同',
                    icon: 'none'
                });
                return;
            }
            
            // 模拟提交数据
            uni.showLoading({
                title: '提交中...'
            });
            
            // 这里可以添加实际的API调用代码
            setTimeout(() => {
                uni.hideLoading();
                uni.showToast({
                    title: '提交成功',
                    icon: 'success'
                });
                
                // 提交成功后返回上一页或跳转到列表页
                setTimeout(() => {
                    uni.navigateBack();
                }, 1500);
            }, 1000);
        }
    }
}
</script>

<style>
.container {
    padding: 30rpx 24rpx;
    background-color: #f5f5f5;
    min-height: 100vh;
	margin-bottom: 200rpx;
}

.page-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 40rpx;
}

.form-container {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 0 24rpx;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.form-item {
    padding: 24rpx 0;
    border-bottom: 1rpx solid #eee;
}

.form-item:last-child {
    border-bottom: none;
}

.form-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 16rpx;
}

.form-input-wrapper {
    position: relative;
}

.form-input {
    width: 100%;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 32rpx;
    color: #333;
}

/* 禁用输入框样式 */
.form-input[disabled] {
    background-color: #f8f8f8;
    color: #666;
}

.form-radio-group {
    display: flex;
    align-items: center;
}

.form-radio-item {
    display: flex;
    align-items: center;
    margin-right: 60rpx;
}

.radio-text {
    font-size: 32rpx;
    color: #333;
    margin-left: 12rpx;
}

.picker {
    width: 100%;
    height: 60rpx;
    line-height: 60rpx;
    font-size: 32rpx;
    color: #333;
}

.date-separator {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 28rpx;
    color: #999;
}

.form-upload-wrapper {
    position: relative;
}

.upload-item {
    position: relative;
    width: 200rpx;
    height: 200rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
    display: inline-block;
}

.upload-preview {
    width: 100%;
    height: 100%;
    border-radius: 8rpx;
}

.upload-delete {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 32rpx;
    height: 32rpx;
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    border-radius: 50%;
    text-align: center;
    line-height: 32rpx;
    font-size: 24rpx;
}

.upload-btn {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #ddd;
    border-radius: 8rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: #fafafa;
}

.upload-icon {
    font-size: 60rpx;
    color: #999;
}

.upload-text {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
}

.upload-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
}

.upload-file-item {
    display: flex;
    align-items: center;
    padding: 16rpx 0;
    border-bottom: 1rpx solid #eee;
}

.file-name {
    font-size: 28rpx;
    color: #333;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.file-size {
    font-size: 24rpx;
    color: #999;
    margin-right: 20rpx;
}

.file-delete {
    font-size: 32rpx;
    color: #999;
}

.auto-gen-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 8rpx;
    padding-left: 4rpx;
}

.submit-btn {
    width: 680rpx;
    height: 88rpx;
    line-height: 88rpx;
    background-color: #007aff;
    color: #fff;
    text-align: center;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin: 60rpx auto 0;
    box-shadow: 0 4rpx 16rpx rgba(0, 122, 255, 0.2);
}
</style>    